package com.example.photography.Activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.example.photography.Model;
import com.example.photography.R;
import com.example.photography.bean.UpdateInfo;
import com.example.photography.common.AppNetConfig;
import com.example.photography.common.BaseActivity;
import com.example.photography.util.Util;
import com.example.photography.view.LoadingDialog;
import com.example.photography.view.Message_Dialog;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;

public class UpdateActivity extends BaseActivity {


    @BindView(R.id.icon_back)
    ImageView iconBack;
    @BindView(R.id.centerTitle)
    TextView centerTitle;
    @BindView(R.id.check_upData)
    LinearLayout checkUpData;
    @BindView(R.id.image_top)
    ImageView imageTop;
    @BindView(R.id.desc_apk)
    TextView descApk;
    @BindView(R.id.source)
    TextView source;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.image_right)
    ImageView imageRight;
    @BindView(R.id.version_new)
    RelativeLayout versionNew;
    private UpdateInfo updateInfo;

    private boolean toActivity = true;//true: 查看本版本apk详情 false:下载apk页面

    /**
     * 拦截返回键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            removeCurrentActivity();
            return true;//拦截返回键
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void initData() {
        initLister();
        getDate();
    }

    private void getDate() {
        //获取数据库版本信息
        updateInfo = Model.getInstance().getUpdateTableDao().getVersion_New();
        String version_db = null;
        if (updateInfo != null) {
            version_db = updateInfo.getVersion();
        }
        //获取当前应用的版本信息
        String version = getVersion();
        //更新页面版本号
        assert version_db != null;
        if (!version_db.equals(version)) {//有新版本未更新
            toActivity = false;
            handler.sendEmptyMessageDelayed(2, 0);
        } else if (version_db.equals(version_db)) {//目前即为最新版本
            toActivity = true;
            handler.sendEmptyMessageDelayed(3, 0);
        }
    }

    private void initLister() {
        checkUpData.setOnClickListener(new View.OnClickListener() {//检测新版本
            @Override
            public void onClick(View view) {
                LoadingDialog.getInstance(UpdateActivity.this).show();
                check_apk();
            }
        });
        iconBack.setOnClickListener(new View.OnClickListener() {//返回键监听
            @Override
            public void onClick(View view) {
                removeCurrentActivity();
            }
        });
        versionNew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (toActivity) {
                    goToActivity(APK_Dec.class, new Bundle());
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("apk_url", updateInfo.apk_url);
                    goToActivity(Update_APK.class, bundle);
                }

            }
        });

    }

    private void check_apk() {
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(AppNetConfig.update, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                //解析json数据
                String jsonData = new String(responseBody);
                try {
                    JSONObject jsonObject = new JSONObject(jsonData);
                    String resultCode = jsonObject.getString("status");
                    if (resultCode.equals("204")) {
                        String data = jsonObject.getString("data");
                        updateInfo = JSON.parseObject(data, UpdateInfo.class);
                        if (updateInfo != null) {//将新版本信息存入数据库
                            Model.getInstance().getUpdateTableDao().addAccount(updateInfo);
                            handler.sendEmptyMessageDelayed(1, 0);
                        } else {
                            message = "检测失败~";
                            handler.sendEmptyMessageDelayed(2, 0);
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                message = "后台君好像生病了~";
                handler.sendEmptyMessageDelayed(0, 0);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_update;
    }

    private String message;
    private Message_Dialog mMyDialog;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            @SuppressLint("SimpleDateFormat")//date转string
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            switch (msg.what) {
                case 0:
                    LoadingDialog.getInstance(UpdateActivity.this).dismiss();
                    Util.show(UpdateActivity.this, message);
                    break;
                case 1:
                    LoadingDialog.getInstance(UpdateActivity.this).dismiss();
                    //获取当前应用的版本信息
                    String version = getVersion();
                    toActivity = version.equals(updateInfo.version);
                    //更新页面版本号
                    //比较服务器获取的最新版本跟本应用的版本是否一致
                    if (toActivity) {
                        Util.showToast(UpdateActivity.this, "当前版本已是最新版本~");
                    } else {
                        View view = getLayoutInflater().inflate(R.layout.message_dialog, null);
                        mMyDialog = new Message_Dialog(UpdateActivity.this, 0, 0, view, R.style.DialogTheme);
                        mMyDialog.setCancelable(true);
                        TextView tv_title = view.findViewById(R.id.tv_title);
                        TextView tv_message = view.findViewById(R.id.tv_message);
                        tv_title.setText("下载最新版本");
                        tv_message.setText(updateInfo.desc_apk);
                        Button btn_cancel = view.findViewById(R.id.btn_cancel);
                        Button btn_confirm = view.findViewById(R.id.btn_confirm);
                        btn_cancel.setText("忽略");
                        btn_confirm.setText("更新");
                        mMyDialog.show();
                        btn_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                mMyDialog.dismiss();
                            }
                        });
                        btn_confirm.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                mMyDialog.dismiss();
                                Bundle bundle = new Bundle();
                                bundle.putString("apk_url", updateInfo.apk_url);
                                goToActivityForResult(Update_APK.class, 1, bundle);
                            }
                        });
                    }
                    break;
                case 2:
                    versionNew.setVisibility(View.VISIBLE);
                    descApk.setText(updateInfo.getDesc_apk());
                    time.setText(df.format(updateInfo.getTime()));
                    break;
                case 3:
                    versionNew.setVisibility(View.VISIBLE);
                    descApk.setText(updateInfo.getDesc_apk());
                    time.setText(df.format(updateInfo.getTime()));
                    imageRight.setImageResource(R.drawable.version);
                    break;

            }
        }
    };

    /**
     * 获取当前版本号
     *
     * @return版本号
     */
    private String getVersion() {
        String version = "未知版本";
        PackageManager manager = getPackageManager();
        try {
            PackageInfo packageInfo = manager.getPackageInfo(getPackageName(), 0);
            version = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            //如果找不到对应的应用包信息，就返回“未知版本”
            e.printStackTrace();
        }
        return version;
    }

    //为了避免出现内存的泄漏，需要在onDestroy()中，移除所有未被执行的消息
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //移除所有的未被执行的消息
        handler.removeCallbacksAndMessages(null);
        //防止窗体泄漏
        if (mMyDialog != null) {
            mMyDialog.dismiss();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:
                    getDate();
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
